package com.example.forum.interceptor;

import com.example.forum.config.AppConfig;
import com.example.forum.model.User;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * 登录拦截器，用于拦截需要登录才能访问的路径
 */
public class LoginInterceptor implements HandlerInterceptor {

    // 静态资源路径前缀
    private static final List<String> STATIC_PATHS = Arrays.asList(
            "/upload/", 
            "/static/", 
            "/css/", 
            "/js/", 
            "/img/", 
            "/fonts/", 
            "/favicon.ico"
    );
    
    // 静态资源文件后缀
    private static final List<String> STATIC_EXTENSIONS = Arrays.asList(
            ".css", ".js", ".jpg", ".jpeg", ".png", ".gif", ".ico", ".svg", ".woff", ".woff2", ".ttf"
    );

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        // 获取当前请求的路径
        String requestURI = request.getRequestURI();
        
        // 打印当前请求路径，便于调试
        
        // 检查是否为图片或其他资源路径
        if (requestURI.contains("/upload/") || 
            requestURI.contains("/images/") || 
            requestURI.contains("/avatars/") ||
            requestURI.endsWith(".jpg") || 
            requestURI.endsWith(".jpeg") || 
            requestURI.endsWith(".png") || 
            requestURI.endsWith(".gif")) {
            // 图片资源，直接放行
            System.out.println("图片资源请求，直接放行: " + requestURI);
            return true;
        }
        
        // 检查是否为静态资源路径
        boolean isStaticResource = false;
        
        // 检查前缀
        for (String path : STATIC_PATHS) {
            if (requestURI.startsWith(path)) {
                isStaticResource = true;
                break;
            }
        }
        
        // 如果前缀检查不通过，则检查文件后缀
        if (!isStaticResource) {
            for (String ext : STATIC_EXTENSIONS) {
                if (requestURI.endsWith(ext)) {
                    isStaticResource = true;
                    break;
                }
            }
        }
        
        // 静态资源直接放行
        if (isStaticResource) {
            return true;
        }
        
        // 获取session
        HttpSession session = request.getSession(false);
        
        // 检查session中是否有用户信息
        if (session != null && session.getAttribute(AppConfig.USER_SESSION) != null) {
            // 已登录，放行
            return true;
        }
        
        // 未登录，返回未授权状态码或重定向到登录页
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 返回401状态码
        response.getWriter().write("{\"code\": 1001, \"message\": \"请先登录\", \"data\": null}");
        return false;
    }
}
